<template>
  <h1>首页</h1>
  <div v-if="user==null">
    <router-link to="/reg">注册</router-link>
    <router-link to="/login">登录</router-link>
  </div>
  <div v-else>
    <h2>欢迎{{ user.nickname }}回来!</h2>
    <router-link to="/post">发微博</router-link>
    <router-link to="/personal">我的微博</router-link>
    <el-button link @click="logout()">退出登录</el-button>
  </div>
  <hr>
  <div v-for="weibo in arr">
    <router-link :to="'/detail?id='+weibo.id">
      <h3>{{ weibo.nickname }}说:{{ weibo.content }}</h3>
      <p>{{weibo.imgUrls}}</p>
<!--  /2024/01/13/xxx.jpg    -->
      <img v-if="weibo.imgUrls!=null"
           v-for="url in weibo.imgUrls.split(',')"
           :src="'http://localhost:8080'+url" width="100">
    </router-link>
  </div>
</template>

<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";

const arr = ref([]);
//进入页面就展示的数据,如果需要发请求,那么发请求的代码都写在onMounted里面
onMounted(() => {
  axios.get('http://localhost:8080/v1/weibos').then((response) => {
    if (response.data.code == 2001) {
      arr.value = response.data.data;
    }
  })
})
const logout = () => {
  if (confirm("您确认退出登录吗?")) {
    localStorage.clear();
    user.value = null; //因为清空LocalStorage并不会让user改变, 页面就不会变, 所以需要手动置为null
  }

}
//取出登录成功时保存的用户对象  需要将JSON格式字符串转成JS对象
const user = ref(localStorage.user ? JSON.parse(localStorage.user) : null);

</script>
